#!/usr/bin/env python
#coding:utf-8

from django import template

from django.utils.safestring import mark_safe
import re
from  django.core.urlresolvers import reverse as url_reverse
register = template.Library()

@register.simple_tag
def article_message(context):
    if context:
       print('========context=========',context)
       return mark_safe(context)



@register.filter
def contains(value,arg):

    if arg in value:
        return  True
    else:
        return False


@register.filter
def sum_size(data_set):
    total_val = sum([i.capacity if i.capacity else 0 for i in data_set])

    return total_val


@register.filter
def list_count(data_set):
    data_count = len([i.capacity if i.capacity else 0 for i in data_set])

    return data_count


@register.simple_tag
def get_table_column(column, table_obj):
    print(table_obj.model_class)
    return  table_obj.model_class._meta.get_field(column).verbose_name


@register.simple_tag
def get_fk_table_column(column, table_obj):
    print(table_obj.model_class)
    dy_fk = getattr(table_obj,table_obj.model_class.dynamic_fk)
    dy_fk_class = getattr(table_obj.model_class,dy_fk)
    # column_name = dy
    # return  table_obj.model_class._meta.get_field(column).verbose_name
    #

@register.simple_tag
def build_table_row(row_obj,table_obj,onclick_column=None,target_link=None):
    # print('--->onclick', onclick_column,)
    # print('--->table_obj.list_display', table_obj.list_display,)
    row_ele = "<tr>"


    for index,column_name in enumerate(table_obj.list_display):
        column_data = row_obj._meta.get_field(column_name)._get_val_from_obj(row_obj)

        # print('== column_data ==',column_data,index)
        # if column_name in table_obj.choice_fields:
        #     column_data = getattr(row_obj,'get_%s_display'%column_name)()

        if column_name in table_obj.fk_fields:
            column_data = getattr(row_obj,column_name).__str__()

        if onclick_column == column_name:
             # if column_name == 'id':
             #    print('== column_name_id ==',column_name)
             #    column_data = index
             # # print('== column_data ==',column_data)

             column = ''' <td><a href=%s>%s</a></td> '''% (url_reverse(target_link,args=(column_data, )),column_data)
        else:
            # print('== column_name ==',column_name)

            column_obj = row_obj._meta.get_field(column_name)
            if column_obj.choices:
                # print ('===column_obj.choices===',column_obj.choices)
                # ===column_obj.choices=== ((0, 'CMD'), (1, 'Login'), (2, 'Logout'), (3, 'GetFile'), (4, 'SendFile'), (5, 'exception'))
                get_column_data = getattr(row_obj,"get_%s_display" % column_name)
                column_data = get_column_data()



            column = "<td>%s</td>" % column_data

        row_ele +=column

    #for dynamic display
    if table_obj.dynamic_fk :
        if hasattr(row_obj,table_obj.dynamic_fk ):
            #print("----dynamic:",getattr(row_obj,table_obj.dynamic_fk), row_obj)
            #print(row_obj.networkdevice)

            dy_fk = getattr(row_obj,table_obj.dynamic_fk) #拿到的是 asset_type的值
            if hasattr(row_obj,dy_fk):
                dy_fk_obj = getattr(row_obj,dy_fk)
                print("-->type",type(dy_fk_obj), dy_fk_obj )
                for index,column_name in enumerate(table_obj.dynamic_list_display):
                    if hasattr(dy_fk_obj,column_name):
                        if column_name in table_obj.dynamic_choice_fields:
                            column_data = getattr(dy_fk_obj, 'get_%s_display' % column_name)()
                        else:
                            column_data = dy_fk_obj._meta.get_field(column_name)._get_val_from_obj(dy_fk_obj)
                        print("dynamic column data", column_data)

                        column = "<td>%s</td>" % column_data
                    else:
                        column = "<td>n/a</td>"
                    row_ele += column
            else:
                #这个关联的表还没创建呢， 但也要创建空的html td占位符
                for index, column_name in enumerate(table_obj.dynamic_list_display):
                    row_ele +="<td></td>"

    for field in table_obj.m2m_fields:
        m2m_obj = getattr(row_obj,field)
        column = "<td> "
        for obj in m2m_obj.select_related():
            column += "<span style='display:inline-block' class='label label-mint label-info'>%s</span>" % obj.__str__()
        column += "</td>"
        row_ele += column
    row_ele += "</tr>"
    return mark_safe(row_ele)

@register.simple_tag
def render_page_num(request,paginator_obj,loop_counter):
    abs_full_url = request.get_full_path()

    if "?page=" in abs_full_url:
        url = re.sub("page=\d+", "page=%s" % loop_counter, request.get_full_path())
    elif "?" in abs_full_url:
        url = "%s&page=%s" % (request.get_full_path(), loop_counter)
    else:
        url = "%s?page=%s" % (request.get_full_path(), loop_counter)


    if loop_counter == paginator_obj.number: #current page
        return mark_safe('''<li class='active'><a href="{abs_url}">{page_num}</a></li>'''\
            .format(abs_url=url,page_num=loop_counter))


    if abs(loop_counter - paginator_obj.number) <2 or \
        loop_counter == 1 or loop_counter == paginator_obj.paginator.num_pages: #the first page or last

        return mark_safe('''<li><a href="{abs_url}">{page_num}</a></li>'''\
            .format(abs_url= url,page_num=loop_counter))
    elif abs(loop_counter - paginator_obj.number) <3:
        return mark_safe('''<li><a href="{abs_url}">...</a></li>'''\
            .format(abs_url=url ,page_num=loop_counter))
    else:
        return ''


@register.simple_tag
def display_orderby_arrow(table_obj,loop_counter):
    if table_obj.orderby_col_index == loop_counter:
        if table_obj.orderby_field.startswith('-'):#降序
            orderby_icon = '''<i class="fa fa-caret-up" aria-hidden="true"></i>'''
        else:
            orderby_icon = '''<i class="fa fa-caret-down" aria-hidden="true"></i>'''
        return mark_safe(orderby_icon)

    return ''

@register.filter
def to_string(value):
    return '%s' % value

@register.simple_tag
def get_filter_field (filter_column,admin_obj):
    print("####### admin obj #########",admin_obj.model ,filter_column)

    field_obj = admin_obj.model._meta.get_field(filter_column)

    select_ele = """<select name="%s"> """ % filter_column

    for choice in field_obj.get_choices():
        selected_condtion = admin_obj.filter_condtions.get(filter_column)
        if selected_condtion != None:                 #if None, 没有过滤这个条件
            print("heoe....",filter_column,selected_condtion,type(selected_condtion))
            if selected_condtion == str(choice[0]):   #就是选择的这个条件
                selected = "selected"
            else:
                selected = ""
        else:
            selected = ""
        option_ele = """<option value="%s" %s>%s</option> """ % (choice[0],selected,choice[1])

        select_ele +=option_ele
    select_ele += "</select>"
    print('==select_ele==',select_ele)
    return mark_safe(select_ele)

                                                #
                                                # <option value="10">10</option>
                                                # <option value="20" selected>20</option>
                                                # <option value="30">30</option>

@register.simple_tag
def  paging_filed_selected(page_number):
    select_ele = ''
    for num in [20,50,100,200]:
       print('---->page_number',page_number)

       if int(page_number) == int(num):
           selected = "selected"

       else:
           selected = ""

       option_ele = """<option value="%s" %s>%s</option> """ % (num,selected,num)
       select_ele += option_ele

    return mark_safe(select_ele)

@register.simple_tag
def get_field_order_by(request):

    current_orderby_key = request.GET.get('orderby')
    print('== current_orderby_key ==',current_orderby_key)
    return current_orderby_key or 20

@register.simple_tag
def get_field_page_num(request):
    current_page_num = request.GET.get('page_num')
    print('== current_orderby_key ==',current_page_num)
    return current_page_num or  20

@register.simple_tag
def get_field_filter(request,admin_list_filter):
    '''
    拼凑出 filter 的URL请求。例如 /host/audit_session/?user=1&bind_host=1&date=2017-08-24
    '''
    abs_full_url = request.get_full_path()
    full_filter_url = ''
    filter_dict = {}


    for filter_condition in admin_list_filter:

            if  filter_condition in abs_full_url:

               filter_list = abs_full_url.split('?')[1].replace('=',':').split('&')
               ss = map(lambda x:filter_dict.setdefault(x.split(':')[0],  x.split(':')[1]) , filter_list)
               print('=========>A----abs_full_url ======', filter_dict,filter_list,ss)
               for i in filter_list:
                  filter_dict[i.split(':')[0]]=i.split(':')[1]

               print('=========>B----abs_full_url ======', filter_dict)


               if filter_dict.get(filter_condition):
                   url = '&%s=%s' % (filter_condition,filter_dict.get(filter_condition))
                   full_filter_url += url
                   print('=========>abs_full_url ======', full_filter_url,url)

    # print('---------> admin_list_filter -------',full_filter_url)

    return full_filter_url or ''


@register.simple_tag
def device_status_display(host):
    # print('---- host.host.asset.device_status_id--->', host.host.asset.device_status_id)
    return  host.host.asset.device_status_choices[host.host.asset.device_status_id-1][1]


@register.simple_tag
#def filter_table(table, field, *args, **kwargs):
def query_set(table_related_field,query_field,string):

    data_set = table_related_field.filter(**{query_field:string}).count()

    return data_set


